package cn.seqdata.rpt.simple.query;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;

import org.springframework.jdbc.core.RowCountCallbackHandler;
import com.google.common.collect.Table;

public abstract class CubeTableCallbackHandler<R> extends RowCountCallbackHandler {
	private final Table<R, String, Object> table;

	public CubeTableCallbackHandler(Table<R, String, Object> table) {
		this.table = table;
	}

	@Override
	protected void processRow(ResultSet rs, int rowNum) throws SQLException {
		R rowKey = rowKey(rs, rowNum);

		if(Objects.nonNull(rowKey)) {
			for(String columnName : getColumnNames()) {
				Object value = rs.getObject(columnName);
				if(Objects.nonNull(value)) {
					table.put(rowKey, camelCase(columnName), value);
				}
			}
		}
	}

	abstract protected R rowKey(ResultSet rs, int rowNum) throws SQLException;

	// sql字段转换为驼峰命名: gov_plant_id ==> govPlantId
	public static String camelCase(String name) {
		StringBuilder sb = new StringBuilder();

		for(int i = 0; i < name.length(); ++i) {
			char c = name.charAt(i);
			if('_' == c && i + 1 < name.length()) {
				c = name.charAt(++i);
				sb.append(Character.toUpperCase(c));
			} else {
				sb.append(c);
			}
		}

		return sb.toString();
	}
}
